import {request as umiRequest} from "umi";
import { jwtDecode } from "jwt-decode";
import md5 from 'crypto-js/md5';

import dayjs from 'dayjs';

import * as reqCfg from "./config"

const buildSign = (postData, secret) => {
    if (typeof postData === 'string') {
        throw new Error('postData类型必须json对象');
    }
    let paramNames = [];
    for (let key in postData) {
        paramNames.push(key);
    }

    paramNames.sort();

    let paramNameValue = [];

    for (var i = 0, len = paramNames.length; i < len; i++) {
        let paramName = paramNames[i];
        paramNameValue.push(paramName);
        paramNameValue.push(postData[paramName]);
    }

    const source = secret + paramNameValue.join('') + secret;
    // console.log("md5***")
    // console.log(md5(source).toString().toUpperCase())
    return md5(source).toString().toUpperCase();
}
/**
 * 请求
 * @param opts.name 接口名
 * @param opts.version 版本号
 * @param opts.method 请求方式
 * @param opts.data 请求数据，json对象
 * @param opts.access_token
 * @param opts.form 表单dom
 * @param opts.callback 响应回调
 * @param opts.jwt jwt
 */
const axios = (url, opts) => {
    const config = reqCfg.CONFIG;

    const name = opts.name;
    const version = opts.version || config.default_version;
    const data = opts.data || {};
    const callback = opts.callback;
    const accessToken = opts.access_token;

    let headers = {};
    let postData = {};

    postData[config.api_name] = name;
    postData[config.version_name] = version;
    postData[config.app_key_name] = config.app_key;
    postData[config.data_name] = encodeURIComponent(JSON.stringify(data));
    postData[config.timestamp_name] = dayjs().format(reqCfg.DATETIME_FORMAT)
    postData[config.format_name] = reqCfg.DEFAULT_FORMAT;

    if(accessToken) {
        postData[config.access_token_name] = accessToken;
    }

    postData[config.sign_name] = buildSign(postData,config.secret);

    let jwt = opts.jwt || config.jwt; // 优先使用opts中的jwt
    if(jwt) {
        const jwtInfo = jwtDecode(jwt);
        console.log("&&&&&&&")
        console.log(jwtInfo)
        console.log(jwtInfo.exp)

        headers['Authorization'] = 'Bearer ' + jwt;
    }

   /* ajax.request({
        url:url
        ,method:opts.method
        ,params:postData
        ,headers:headers
        ,form:opts.form
        ,callback:callback
        ,error:opts.error
    });*/

    return umiRequest(url, {
        method: opts.method,
        params: postData,
        // data: postData,
        headers: headers,
        timeout: reqCfg.TIMEOUT,

        skipErrorHandler: true,
        getResponse: false,
        requestInterceptors: [],
        responseInterceptors: [],
    })
}

export const request = {
    post: (url, opts)=> {
        opts.method = reqCfg.POST_TYPE;
        return axios(url, opts);
    },
    get: (url, opts) => {
        if(opts.form) {
            throw new Error('get方式不支持上传功能');
        }
        opts.method = reqCfg.GET_TYPE;
        axios(url, opts);
    }
}